package com.hsd.znsh.security.app;

import com.hsd.znsh.entity.User;
import com.hsd.znsh.enums.DeletedStatusEnum;
import com.hsd.znsh.enums.UserRoleEnum;
import com.hsd.znsh.repository.UserRepository;
import com.hsd.znsh.service.RedisService;
import com.hsd.znsh.utils.EnumUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class APPUserDetailsService implements UserDetailsService {

	private UserRepository userRepository;

    public APPUserDetailsService(UserRepository userRepository){
    	this.userRepository=userRepository;
	}


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user=userRepository.findByUsernameAndDeleted(username, DeletedStatusEnum.NOT_DELETED.getCode());
		if(user.getUserType()!=UserRoleEnum.APP_MANAGER.getCode()){
			throw new UsernameNotFoundException("用户名不存在");
		}
        if(user!=null){
			List<GrantedAuthority> authorities=new ArrayList<>();
			String role="ROLE_"+ EnumUtil.getEnumByCode(user.getUserType(),UserRoleEnum.class).name();
			authorities.add(new SimpleGrantedAuthority(role));
			user.setAuthorities(authorities);
			return user;
		}
        throw new UsernameNotFoundException("用户名不存在");
	}


}
